package com.cloudkinto.controller.fbaorderoutput;


import com.cloudkinto.base.BaseController;
import com.cloudkinto.common.annotations.UserSessionRequired;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.service.fbaorderoutput.FbaOrderOutputService;
import com.cloudkinto.service.fbaorderoutput.vo.*;
import com.cloudkinto.service.orderoutput.vo.*;
import com.cloudkinto.service.stock.StockRecordService;
import com.cloudkinto.service.stock.vo.record.StockRecordPageRes;
import com.cloudkinto.service.tailtrucks.TailTrucksService;
import com.cloudkinto.service.tailtrucks.vo.FbaOrderSingleJointReq;
import com.cloudkinto.service.tailtrucks.vo.TailTrucksJointFbaReq;
import io.swagger.annotations.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 张永远
 * @since 2020-06-04
 */
@RestController
@Api(tags = "Fba出库订单模块")
@RequestMapping("/api/admin/fbaOrderOutput")
public class FbaOrderOutputController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(FbaOrderOutputController.class);

    @Autowired
    private FbaOrderOutputService service;
    @Autowired
    private StockRecordService stockRecordService;
    @Autowired
    private TailTrucksService tailTrucksService;


    @UserSessionRequired
    @GetMapping("/addInit")
    @ApiOperation(value = "新增初始化", notes = "新增初始化")
    public SingleResult addInit() {
        Long companyId = getCompanyId();
        return service.addInit(getCurrentUserId(), companyId);
    }

    @UserSessionRequired
    @PostMapping("fbaReturnAdd")
    @ApiOperation(value = "fba转运新增", notes = "新增")
    public SingleResult fbaStorageAdd(@RequestBody @Validated FbaOrderOutputAddReq req) {
        Long userId = getCurrentUserId();
        if (req.getCompanyId() == null || req.getCompanyId() == 0) {
            req.setCompanyId(getCompanyId());
        }
        return SingleResult.success("新增成功", service.fbaStorageAdd(req, userId));
    }

    @UserSessionRequired
    @GetMapping("setCost")
    @ApiOperation(value = "设置费用", notes = "设置费用")
    public SingleResult setCost(@RequestParam Long id, @RequestParam double fee) {
        Long userId = getCurrentUserId();
        return service.setCost(id, fee, userId);
    }

    @UserSessionRequired
    @PostMapping("computationalCosts")
    @ApiOperation(value = "费用预算", notes = "费用预算")
    public SingleResult computationalCosts(@RequestBody @Validated FbaOrderOutputComputationalCostsReq req) {
        Long companyId = req.getCompanyId();
        return SingleResult.success(service.computationalCosts(req, companyId));
    }

    @UserSessionRequired
    @GetMapping("/updateInit/{id}")
    @ApiOperation(value = "编辑初始化", notes = "编辑初始化")
    @ApiResponses({@ApiResponse(code = 200, message = "", response = OrderOutputDetailRes.class)})
    public SingleResult<OrderOutputDetailRes> updateInit(@PathVariable("id") Long id) {
        return service.updateInit(id,getCompanyId());
    }

    @UserSessionRequired
    @PutMapping("/update")
    @ApiOperation(value = "修改", notes = "修改")
    public SingleResult update(@RequestBody @Validated FbaOrderOutputUpdateReq req) {
        Long userId = getCurrentUserId();
        return SingleResult.success("修改成功", service.update(req, userId));
    }

    @UserSessionRequired
    @PostMapping("/set/appointmentStorageTime")
    @ApiOperation(value = "设置约仓时间", notes = "修改")
    public SingleResult appointmentStorageTime(@RequestBody @Validated FbaOrderOutputUpdateTimeReq req) {
        service.appointmentStorageTime(req, getCurrentUserId());
        return SingleResult.success();
    }

    @UserSessionRequired
    @PostMapping("/set/appointmentCarTime")
    @ApiOperation(value = "设置约车时间", notes = "修改")
    public SingleResult appointmentCarTime(@RequestBody @Validated FbaOrderOutputUpdateTimeReq req) {
        service.appointmentCarTime(req, getCurrentUserId());
        return SingleResult.success();
    }

    @UserSessionRequired
    @PostMapping("/updateTrackNumber")
    @ApiOperation(value = "修改快递单号和快递公司", notes = "修改快递单号和快递公司")
    public SingleResult updateTrackNumber(@RequestBody @Validated FbaOrderOutputUpdateTrackNumberReq req) {
        Long userId = getCurrentUserId();
        return SingleResult.success("修改成功", service.updateTrackNumber(req, userId));
    }

    @UserSessionRequired
    @GetMapping("/updateTrackNumberInit")
    @ApiOperation(value = "修改快递单号和快递公司初始化", notes = "修改快递单号和快递公司初始化")
    public SingleResult updateTrackNumberInit(Long id) {
        Long userId = getCurrentUserId();
        return SingleResult.success("查询成功", service.updateTrackNumberInit(id, userId,getCompanyId()));
    }

    @UserSessionRequired
    @PostMapping("/order/uploadSignatureFile")
    @ApiOperation(value = "签收单回传", notes = "截单")
    public SingleResult uploadSignatureFile(@RequestBody @Validated FbaOrderOutputUploadFileReq req) {
        Long userId = getCurrentUserId();
        service.uploadSignatureFile(req, userId);
        return SingleResult.success("上传成功", null);
    }

    @UserSessionRequired
    @PostMapping("/order/uploadSTrackFile")
    @ApiOperation(value = "上传快递标签", notes = "上传快递标签")
    public SingleResult uploadSTrackFile(@RequestBody @Validated FbaOrderOutputUploadFileReq req) {
        Long userId = getCurrentUserId();
        service.uploadSTrackFile(req,userId);
        return SingleResult.success("上传成功", null);
    }

    @UserSessionRequired
    @DeleteMapping("/{id}")
    @ApiOperation(value = "根据id删除", notes = "根据id删除")
    public SingleResult delete(@PathVariable("id") Long id) {
        Long userId = getCurrentUserId();
        return SingleResult.success("删除成功", service.delete(id, userId));
    }

    @UserSessionRequired
    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查看详情", notes = "根据id查看详情")
    @ApiResponses({@ApiResponse(code = 200, message = "", response = OrderOutputDetailRes.class)})
    public SingleResult<FbaOrderOutputDetailRes> detail(@PathVariable("id") Long id) {
        return SingleResult.success("查询成功", service.detail(id));
    }

    @UserSessionRequired
    @GetMapping("/pageInit")
    @ApiOperation(value = "查询初始化", notes = "查询初始化")
    public SingleResult pageInit() {
        return service.pageInit(getCompanyId(), getCurrentUserId());
    }

    @UserSessionRequired
    @GetMapping("/list")
    @ApiOperation(value = "查询", notes = "查询")
    @ApiImplicitParams(@ApiImplicitParam(value = "关键字（模糊查询）", name = "keyword", paramType = "query", dataType = "String"))
    public SingleResult list(HttpServletRequest request) {
        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        String keyword = request.getParameter("keyword");
        map.put("keyword", keyword);
        return SingleResult.success("查询成功", service.getList(map));
    }

    @UserSessionRequired
    @GetMapping("/listPage")
    @ApiOperation(value = "查询（分页）", notes = "查询（分页）")
    @ApiImplicitParams({@ApiImplicitParam(name = "keyword", value = "关键字搜索", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "keyword", value = "关键字搜索", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "页大小", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "订单状态", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "multi", value = "包裹类型  1 一单一件 2一单多件", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "trackId", value = "快递公司", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "pickStatus", value = "拣货状态",  paramType = "query"),
            @ApiImplicitParam(name = "storageId", value = "仓库id", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "shopId", value = "店铺id", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "storageId", value = "仓库id", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "startDate", value = "开始时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endDate", value = "结束时间", dataType = "String", paramType = "query")})
    @ApiResponses({@ApiResponse(code = 200, message = "", response = OrderOutputListRes.class)})
    public PageResult<OrderOutputListRes> listPage(String keyword, String current, String pageSize, String multi, String fbaStorageId,
                                                   String status, String startDate, String endDate, String trackId, String pickStatus,String shopId, String storageId, String isTrucks) {
        Long companyId = getCompanyId();
        Map<String, String> map = new HashMap<>();
        map.put("keyword", keyword);
        map.put("current", current);
        map.put("pageSize", pageSize);
        map.put("status", status);
        map.put("multi", multi);
        map.put("fbaStorageId", fbaStorageId);
        map.put("startDate", startDate);
        map.put("endDate", endDate);
        map.put("trackId", trackId);
        map.put("storageId", storageId);
        map.put("isTrucks", isTrucks);
        if (StringUtils.isNotBlank(pickStatus)) {
            map.put("pickStatus", pickStatus);
        }
//        map.put("shopId", shopId);
//        map.put("orderType", "2");//fba转运
        if (companyId != null) {
            map.put("companyId", companyId + "");
        }
        if (shopId != null) {
            map.put("companyId", shopId);
        }
        return service.getListPage(map);
    }

//    @UserSessionRequired
//    @PostMapping("/uploadExcel")
//    @ApiOperation(value = "导入发货单Excel", notes = "导入发货单Excel")
////    @ApiImplicitParams({@ApiImplicitParam(name = "file",value = "导入文件"  ,paramType = "file"), @ApiImplicitParam(name = "shopId", value = "店铺id"), @ApiImplicitParam(name = "storageId", value = "仓库id")})
//    public SingleResult uploadExcel(MultipartFile file, Integer storageId, Integer shopId) {
//        Long userid = getCurrentUserId();
//        List<String> dataErrors = service.dealwithExcel(file, storageId, shopId, userid);
//        return SingleResult.success(dataErrors);
//    }

    @UserSessionRequired
    @GetMapping("/uploadExcelInit")
    @ApiOperation(value = "导入发货单Init", notes = "导入发货单ExcelInti")
//    @ApiImplicitParams({@ApiImplicitParam(name = "file",value = "导入文件"  ,paramType = "file"), @ApiImplicitParam(name = "shopId", value = "店铺id"), @ApiImplicitParam(name = "storageId", value = "仓库id")})
    public SingleResult uploadExcelInit() {
        Long userid = getCurrentUserId();
        List<Map> dataErrors = service.uploadExcelInit(userid);
        return SingleResult.success(dataErrors);
    }

    @UserSessionRequired
    @PostMapping("/uploadTrackNumberExcel")
    @ApiOperation(value = "导入快递单Excel", notes = "导入快递单Excel")
//    @ApiImplicitParams({@ApiImplicitParam(name = "file",value = "导入文件"  ,paramType = "file"), @ApiImplicitParam(name = "shopId", value = "店铺id"), @ApiImplicitParam(name = "storageId", value = "仓库id")})
    public SingleResult uploadTrackNumberExcel(MultipartFile file, Integer storageId) {
        Long userid = getCurrentUserId();
        List<String> dataErrors = service.dealwithTrackNumberExcel(file, storageId, userid);
        return SingleResult.success(dataErrors);
    }

    @UserSessionRequired
    @PostMapping("exportExcel")
    @ApiOperation(value = "导出所有数据excel")
    public void exportAll(@RequestBody OrderOutputExportReq req, HttpServletResponse response) throws Exception {

        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        map.put("keyword", req.keyword);
        map.put("current", req.current);
        map.put("pageSize", req.pageSize);
        map.put("status", req.status);
        map.put("multi", req.multi);
        map.put("startDate", req.startDate);
        map.put("endDate", req.endDate);
        map.put("trackId", req.trackId);
        map.put("storageId", req.storageId);
        map.put("fbaStorageId", req.fbaStorageId);
//        map.put("orderType", "2");//fba转运
        if (companyId != null) {
            map.put("companyId", companyId + "");
        }
        if (req.shopId != null) {
            map.put("companyId", req.shopId);
        }
        service.exportExcel(map, req.ids, response);
    }

    @UserSessionRequired
    @PostMapping("exportTrackExpress")
    @ApiOperation(value = "导出快递公司面单")
    public void exportTrackExpress(@RequestBody OrderOutputExportReq req, HttpServletResponse response) throws Exception {
        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        map.put("keyword", req.keyword);
        map.put("current", req.current);
        map.put("pageSize", req.pageSize);
        map.put("status", req.status);
        map.put("multi", req.multi);
        map.put("startDate", req.startDate);
        map.put("endDate", req.endDate);
        map.put("trackId", req.trackId);
        map.put("storageId", req.storageId);
        map.put("fbaStorageId", req.fbaStorageId);
//        map.put("orderType", "2");//fba转运
        if (companyId != null) {
            map.put("companyId", companyId + "");
        }
        if (req.shopId != null) {
            map.put("companyId", req.shopId);
        }
        service.exportTrackExpress(map, req.ids, response);
    }

    @UserSessionRequired
    @GetMapping("updateFbaStatusInit")
    @ApiOperation(value = "FBA更新/审核初始化")
    public SingleResult updateStatusInit(Long orderId) throws Exception {
        return service.updateFbaStatusInit(orderId, getCurrentUserId());
    }

    @UserSessionRequired
    @PostMapping("updateFbaStatus")
    @ApiOperation(value = "FBA更新/审核")
    public SingleResult updateStatus(@RequestBody FbaOrderUpdateStatusReq req) throws Exception {
        return SingleResult.success(service.updateFbaStatus(req.id, req.status, req.sysTips, getCurrentUserId()));
    }

    @UserSessionRequired
    @PostMapping("updateOrderWaitSend")
    @ApiOperation(value = "更改订单为待发货状态")
    public SingleResult updateOrderWaitSend(@RequestBody OrderOutputExportReq req, HttpServletResponse response) throws Exception {
        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        map.put("keyword", req.keyword);
        map.put("current", req.current);
        map.put("pageSize", req.pageSize);
        map.put("status", req.status);
        map.put("multi", req.multi);
        map.put("startDate", req.startDate);
        map.put("endDate", req.endDate);
        map.put("trackId", req.trackId);
        map.put("storageId", req.storageId);
        map.put("fbaStorageId", req.fbaStorageId);
//        map.put("orderType", "2");//fba转运
        if (companyId != null) {
            map.put("companyId", companyId + "");
        }
        if (req.shopId != null) {
            map.put("companyId", req.shopId);
        }
        return service.updateOrderWaitSend(map, req.ids, response);
    }

    @UserSessionRequired
    @PostMapping("exportSkuTotal")
    @ApiOperation(value = "导出所有SKU小计")
    public void exportSkuTotal(@RequestBody OrderOutputExportReq req, HttpServletResponse response) throws Exception {
        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        map.put("keyword", req.keyword);
        map.put("current", req.current);
        map.put("pageSize", req.pageSize);
        map.put("status", req.status);
        map.put("multi", req.multi);
        map.put("startDate", req.startDate);
        map.put("endDate", req.endDate);
        map.put("trackId", req.trackId);
        map.put("storageId", req.storageId);
//        map.put("orderType", "2");//fba转运
        if (companyId != null) {
            map.put("companyId", companyId + "");
        }
        if (req.shopId != null) {
            map.put("companyId", req.shopId);
        }
        map.put("fbaStorageId", req.fbaStorageId);
        service.exportSkuTotal(map, req.ids, response);
    }
    @UserSessionRequired
    @PostMapping("exportOrderFbaFile")
    @ApiOperation(value = "导出FBA标签文件（多文件）")
    public SingleResult exportPickExcel(Long id ,int type) throws Exception {
        Long companyId = getCompanyId();
       return SingleResult.success(service.exportOrderFbaFile( id,type));
    }

    @UserSessionRequired
    @PostMapping("exportPickExcelOne")
    @ApiOperation(value = "导出拣货单")
    public void exportPickExcel(Long id , HttpServletResponse response) throws Exception {
        Long companyId = getCompanyId();
        service.exportPickExcelOne( id, response);
    }

    @UserSessionRequired
    @PostMapping("exportPickExcel")
    @ApiOperation(value = "导出拣货单")
    public void exportPickExcel(@RequestBody OrderOutputExportReq req, HttpServletResponse response) throws Exception {
        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        map.put("keyword", req.keyword);
        map.put("current", req.current);
        map.put("pageSize", req.pageSize);
        map.put("status", req.status);
        map.put("multi", req.multi);
        map.put("startDate", req.startDate);
        map.put("endDate", req.endDate);
        map.put("trackId", req.trackId);
        map.put("storageId", req.storageId);
//        map.put("orderType", "2");//fba转运
        if (companyId != null) {
            map.put("companyId", companyId + "");
        }
        if (req.shopId != null) {
            map.put("companyId", req.shopId);
        }
        map.put("fbaStorageId", req.fbaStorageId);
        service.exportPickExcel(map, req.ids, response);
    }



    @UserSessionRequired
    @PostMapping("/exportPickUp")
    @ApiOperation(value = "批量拣货后导出拣货单", notes = "批量拣货后导出拣货单")
    public void exportPickUp(@RequestBody ExportPickUpReq req, HttpServletResponse response) throws IOException {
        service.exportPickUp(req.getIds(), response);
    }



    @UserSessionRequired
    @GetMapping("/stockRecordListPage")
    @ApiOperation(value = "仓库商品查询（分页）", notes = "查询（分页）")
    @ApiImplicitParams({@ApiImplicitParam(name = "keyword", value = "关键字搜索", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "页大小", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "storageId", value = "仓库id", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "shopId", value = "店铺id", dataType = "String", paramType = "query")})
    @ApiResponses({@ApiResponse(code = 200, message = "", response = StockRecordPageRes.class)})
    public PageResult<StockRecordPageRes> stockRecordListPage(HttpServletRequest request) {
        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        String keyword = request.getParameter("keyword");
        String shopId = request.getParameter("shopId");
        String storageId = request.getParameter("storageId");
        String current = request.getParameter("current");
        String size = request.getParameter("pageSize");
        String productType = request.getParameter("productType");

        map.put("keyword", keyword);
        map.put("productType", productType);
        map.put("storageId", storageId);
        map.put("shopId", shopId);
        if (companyId != null) {
            map.put("companyId", companyId + "");
        }
//        if (shopId != null) {
//            map.put("companyId", shopId);
//        }
        map.put("current", current);
        map.put("pageSize", size);
        return stockRecordService.getListPage(map);
    }

    @UserSessionRequired
    @PostMapping("/importExcel")
    @ApiOperation(value = "导入入库单信息", notes = "导入入库单信息")
    public SingleResult uploadExcel(MultipartFile file, Long storageId, Long shopId) throws IOException {
        Long userId = getCurrentUserId();
        return SingleResult.success(service.importExcel(file, storageId, shopId ,getCompanyId()));
    }


    @UserSessionRequired
    @PostMapping("jointTrucks")
    @ApiOperation(value = "拼单", notes = "费用预算")
    public SingleResult jointTrucks(@RequestBody @Validated TailTrucksJointFbaReq req) {
        tailTrucksService.jointFbaTrucks(req, getCurrentUserId());
        return SingleResult.success();
    }


    @UserSessionRequired
    @PostMapping("fbaOrderSingleJoint")
    @ApiOperation(value = "单个转运单拼单", notes = "费用预算")
    public SingleResult fbaOrderSingleJoint(@RequestBody @Validated FbaOrderSingleJointReq req) {
        return tailTrucksService.fbaOrderSingleJoint(req, getCurrentUserId());

    }

    @UserSessionRequired
    @GetMapping("fbaOrderSingleJointInit")
    @ApiOperation(value = "单个转运单拼单初始化", notes = "费用预算")
    public SingleResult jointTrucks(@RequestParam Long id) {
        return tailTrucksService.fbaOrderSingleJointInit(id);

    }

    @UserSessionRequired
    @PostMapping("batchPickUp")
    @ApiOperation(value = "批量拣货", notes = "批量拣货")
    @ApiResponses({@ApiResponse(code = 200, message = "", response = BatchPickUpRes.class)})
    public SingleResult batchPickUp(@RequestBody BatchPickUpReq req) {
        return SingleResult.success(service.batchPickUp(req, getCurrentUserId(), getCompanyId()));
    }

}

